package com.lingkang.flychat.websocket;


import android.os.Handler;
import android.os.Message;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.LogUtils;
import com.lingkang.flychat.config.UrlConfig;
import com.orhanobut.hawk.Hawk;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

public class WebsocketClient extends WebSocketListener {
    public static int num = 0;

    public static boolean status = false;
    public static WebSocket webSocket;
    private Handler handler;

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void onClosed(WebSocket webSocket, int code, String reason) {
        super.onClosed(webSocket, code, reason);
        LogUtils.d(reason);
        status = false;
        retry();
    }

    @Override
    public void onClosing(WebSocket webSocket, int code, String reason) {
        super.onClosing(webSocket, code, reason);
        LogUtils.d(reason);
        status = false;
        retry();
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
        super.onFailure(webSocket, t, response);
        LogUtils.d(response);
        status = false;
        retry();
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        super.onMessage(webSocket, text);
        LogUtils.d(text);
    }

    @Override
    public void onMessage(WebSocket webSocket, ByteString bytes) {
        super.onMessage(webSocket, bytes);
        LogUtils.d(bytes);
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        webSocket.send("hello");
        this.webSocket = webSocket;
        status = true;
    }

    private synchronized void retry() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                WebsocketClient websocketClient = new WebsocketClient();
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(UrlConfig.ws + "?" + Hawk.get("token"))
                        .build();
                client.newWebSocket(request, websocketClient);
                client.dispatcher().executorService().shutdown();
                ++num;
                Message message = new Message();
                message.what = 12;
                message.obj = "重连..." + num;
                if (handler != null)
                    handler.sendMessage(message);
                LogUtils.d("重连..." + num);
            }
        }).start();
    }
}
